<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/16
 * Time: 19:55
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\system;

use app\admin\controller\BaseController;
use app\common\model\AccountPlatform;
use app\common\service\platform\BasePlatformService;
use app\common\service\system\AccountService;
use think\facade\Validate;

class PlatformController extends BaseController
{
    /**
     * 平台首页
     * @return string
     * @date 2020/09/17
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $where = [];
            $order = "sort desc,name";
            $this->assign("list", AccountPlatform::where($where)->order($order)->select());
            return $this->fetch('lists');
        }
        return $this->fetch('index');
    }

    /**
     * 保存
     * @date 2020/09/17
     * @author longli
     */
    public function save()
    {
        if(!$this->request->isPost()) $this->error('非法操作');
        $post = $this->request->post();
        $validate = Validate::make([
            'name'  => 'require|max:50',
            'code' => 'max:3',
            'classes' => function($value, $rule)
            {
                if(empty($value)) return true;
                if(!BasePlatformService::classesExist($value))return "对接类【{$value}】不存在";
                return true;
            }
        ],[
            'name.require' => '平台名称必填',
            'name.max'     => '名称最多不能超过50个字符',
            'code.max'     => '平台代码只能输入三位',
        ]);
        if(!$validate->batch()->check($post))$this->error(join(', ', $validate->getError()));
        AccountService::getInstance()->addPlatform($post)
            ? $this->success('保存成功')
            : $this->error('保存失败');
    }

    /**
     * 锁定
     * @date 2020/09/17
     * @author longli
     */
    public function lock()
    {
        $pid = $this->request->get("platform_id");
        if(empty($pid)) $this->error('非法操作');
        $status = $this->request->get("lock");
        AccountPlatform::get($pid)->save(compact('status'));
        $this->success('操作成功');
    }

    /**
     * 删除
     * @date 2020/09/17
     * @author longli
     */
    public function delete()
    {
        $pid = $this->request->get("platform_id");
        if(empty($pid)) $this->error('非法操作');
        AccountPlatform::destroy($pid)
            ? $this->success('删除成功')
            : $this->error('删除失败');
    }

    /**
     * 编辑
     * @return string
     * @date 2020/09/17
     * @author longli
     */
    public function add()
    {
        $this->assign("service", BasePlatformService::getAllPlatformService());
        $pid = $this->request->get("platform_id");
        if(!empty($pid)) $this->assign("platform", AccountPlatform::get($pid));
        return $this->fetch("add");
    }
}